package dq.study.concurrent.semaphore;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * @author dongqun
 * @version 1.0
 * @description tryAcquire
 * @date 2019/9/5 19:03
 */
public class SemaphoreService3 implements ISemaphoreService{

    private Semaphore semaphore = new Semaphore(1,true);


    public void doSomething(){
        try {
            if (semaphore.tryAcquire(1,3,TimeUnit.SECONDS)){
                System.out.println(Thread.currentThread().getName()+":doSomething--start:"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
                Thread.sleep(2000);
                System.out.println(Thread.currentThread().getName()+":doSomething--end:"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))+"当前受否有等待任务："+semaphore.hasQueuedThreads()+"等待进程数："+semaphore.availablePermits());
                semaphore.release(1);
            }else {
                System.out.println(Thread.currentThread().getName()+":doSomething--没有获取到许可准备退出:"+LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            semaphore.release(1);
        }
    }


    public int availablePermits(){
        return semaphore.availablePermits();
    }

}
